const oImgFileSelector = document.querySelector('#imgFileSelector');
const oOriginImgPreview = document.querySelector('#originImgPreview');
const oCompressedImgPreview = document.querySelector('#compressedImgPreview');
const reader = new FileReader(); // 读文件
let imgFile = null
let quality = 90
let compressedImgSrc = ''
const IMG_TYPES = {
  'image/jpeg': 'image/jpeg',
  'image/png': 'image/png',
  'image/webp': 'image-webp',
}
function init(){
  bindEvent()
}
function bindEvent(){
  oImgFileSelector.addEventListener('change',handleFileSelectorChange,false)
}
function handleFileSelectorChange(e){
  // e 事件对象
  // e.target.files 数组
  // e.target.files[0] // 需要的对象
  imgFile = e.target.files[0];
  if(!imgFile || !IMG_TYPES[imgFile.type]){
    alert('请上传正确格式的图片')
    setImgFileEmpty()
    setImgPreviewVisible(oOriginImgPreview,false)
    setImgPreviewVisible(oCompressedImgPreview,false)
    return;
  }
  setImgPreview(imgFile)
}
function setImgFileEmpty(){
  oImgFileSelector.value = ''
  imgFile = null
}
function setImgPreviewVisible(node,visible){
  switch (visible){
    case true:
      node.classList.remove('hide');
      node.classList.add('show');
      break;
    case false:
      node.classList.remove('show');
      node.classList.add('hide');
      break;
    default:
      break;
  }
}
function setImgPreview(imgFile){
  if(imgFile instanceof File){
    reader.onload = async function(){
      const originImgSrc = reader.result;
      let compressedImgSrc = await createCompressedImage({
        imgSrc:originImgSrc,
        quality:90,
        type:imgFile.type
      })
      oOriginImgPreview.src = originImgSrc;
      setImgPreviewVisible(oOriginImgPreview,true)
      oCompressedImgPreview.src = compressedImgSrc;
      setImgPreviewVisible(oCompressedImgPreview,true)
    }
    reader.readAsDataURL(imgFile); // 转base64
  }
}
function createCompressedImage({imgSrc,type}){
  const oCan = document.createElement('canvas');
  const oImg = document.createElement('img');
  const ctx = oCan.getContext('2d')
  oImg.src = imgSrc;
  return new Promise((resolve, reject) => {
    oImg.onload = function(){
      const imgWidth = oImg.width;
      const imgHeight = oImg.height;
      oCan.width = imgWidth;
      oCan.height = imgHeight;
      ctx.drawImage(oImg,0,0,imgWidth,imgHeight);
      doCompress(oCan,imgSrc,imgFile.type)
      resolve(compressedImgSrc)
    }
  })
}
function doCompress(canvas,imgSrc,type){
  compressedImgSrc = canvas.toDataURL(type,quality/100);
  console.log(quality)
  if(compressedImgSrc.length >= imgSrc.length && quality>0){
    quality-=5
    doCompress(canvas,imgSrc,type)
  }
}
init()